﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.UTIL;

namespace CRM.WEB
{
    public partial class SaveAliCode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string code = Request["code"];
            string fl = FileHelper.Read(Server.MapPath("/Static/AliFile/alikey.txt"));
            Hashtable hs = (Hashtable)JSON.Decode(fl);
            hs["code"] = code;
            string strAppKey = hs["appKey"].ToString();
            string strAppSecret = hs["appSecret"].ToString();
            //下面是获得token
            //https://gw.api.alibaba.com/openapi/http/1/system.oauth2/getToken/YOUR_APPKEY?grant_type=authorization_code&need_refresh_token=true&client_id= YOUR_APPKEY&client_secret= YOUR_APPSECRET&redirect_uri=YOUR_REDIRECT_URI&code=CODE

            string postString = "grant_type=authorization_code&need_refresh_token=true&client_id=" + strAppKey + "&client_secret=" + strAppSecret + "&redirect_uri=LOCALHOST&code=" + code;
            byte[] postData = Encoding.UTF8.GetBytes(postString);//编码，尤其是汉字，事先要看下抓取网页的编码方式  

            string url = ConfigurationManager.AppSettings["GetTokenWithCodeUrl"] + strAppKey;//地址  

            var webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可  
            try
            {
                byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流
                string srcString = Encoding.UTF8.GetString(responseData);//解码   
                Hashtable ht = (Hashtable)JSON.Decode(srcString);
                hs["aliId"] = ht["aliId"];
                hs["access_token"] = ht["access_token"];
                hs["access_token_time"] = DateTime.Now.ToString(CultureInfo.InvariantCulture);
                hs["refresh_token"] = ht["refresh_token"];
                hs["refresh_token_timeout"] = ht["refresh_token_timeout"];
                FileHelper.Write(Server.MapPath("/Static/AliFile/alikey.txt"), JSON.Encode(hs));
                Response.Redirect("/Default.aspx");
            }
            catch (Exception exinfo)
            {
                Response.Write(exinfo.ToString());

            }
        }
    }
}